package cn.baker.app.config;

import cn.baker.app.common.Constants;
import cn.baker.app.consmer.MyConsumer;
import cn.baker.rabbitmq.common.TransRabbitMqConstants;
import cn.baker.rabbitmq.config.TransRabbitConfig;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yuanyu
 */
@Configuration
@AutoConfigureAfter(TransRabbitConfig.class)
public class RabbitmqConfig {
    /**
     * 队列
     */
    @Bean
    public Queue directQueue() {
        return new Queue(Constants.TRANSACTION_QUEUE_NAME);
    }

    /**
     * 交换机
     */
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(Constants.TRANSACTION_EXCHANGE_NAME);
    }

    /**
     * 绑定队列与交换机
     */
    @Bean
    public Binding bindingDirect() {
        return BindingBuilder.bind(directQueue()).to(directExchange()).with(Constants.TRANSACTION_KEY);
    }

    /**
     * MessageListenerContainer消息监听容器
     *
     * @param collectionFactory 连接工厂，需要指定 TransRabbitMqConstants.TRANS_RABBIT_CONNECTION_FACTORY
     * @param myConsumer        接收消息需要实现AbstractMessageListener
     * @return
     */
    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer(@Qualifier(TransRabbitMqConstants.TRANS_RABBIT_LISTENER_CONTAINER_FACTORY) SimpleRabbitListenerContainerFactory collectionFactory, MyConsumer myConsumer) {
        SimpleMessageListenerContainer messageListenerContainer = collectionFactory.createListenerContainer();
        // 设置监听的队列
        messageListenerContainer.setQueueNames(Constants.TRANSACTION_QUEUE_NAME);
        // 使用Channel
        messageListenerContainer.setExposeListenerChannel(true);
        // 手动确认消息
        messageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // 置自己编写的监听器
        messageListenerContainer.setMessageListener(myConsumer);


        return messageListenerContainer;
    }

}
